$(document).on("ready", function(){
    $("#search-button").on("click",function(){
       if($("#searchtext").val()==''){
           $("#search-error-msg").html("<div class='alert'>Please enter a search value</div>");
           return false;
       }
       $("#search-form").submit();
    });
    
    // Active File on the list
    $("#main").on("click", ".selectList li a", function(event){
        event.preventDefault();
        
        $(this).parents(".selectList").find("li a").not(this).removeClass("active");
        
        if ($(this).hasClass("active")){
            $(this).removeClass("active");
        }else{
            $(this).addClass("active");
        }        
    });


    // Show Custom link
    /*
    $("input[name='question']").on("mouseup", function(event){
    	event.preventDefault();
    	var id = $(this).data("id");   	

    	// Uncheck and hide "custom" others questions
    	$("input[name='question']").not(this).attr("checked", false);
    });

    // Check checked questions
    $("input[name='question']").on("change", function(){
    	checkChecked();
    });
    */

    // Open Modal of Questions and fill selects
    $("#modalFiles").dialog({
        autoOpen: false,
        minHeight: 500,
        minWidth: 650,
        modal: true,
        buttons: {
            "Ok": function(){
                var id = $("#idOpened").val();
                $(this).dialog( "close" );
                saveTransfers(id);          
            },
            "Cancel": function(){
                $(this).dialog( "close" );
                cleanSelects();
            }
        }
    });
    $("#main").on("click", ".showQuestions", function(event){
        event.stopPropagation();
    	event.preventDefault();
        var id = $(this).data("id");
        
    	// Open Modal
        $("#modalFiles").dialog("open");

    	// Fill Selects
        fillSelects(id);
    });

    // Transfer files between selects in modal
    $(".btn_transfer").on("click", function(){
        var action = $(this).data("action");
        
        transferFiles(action);
    });
    
    // Filter Files
    $("#filter_files").on("submit", function(event){
        var bucket = $("#bucketName").val(),
            prefix = $("#prefix").val(),
            error = "";
            
        if (bucket == null || bucket == undefined || bucket == ""){
            error += "Bucket is required <br />";
        }
        if (prefix == null || prefix == undefined || prefix == ""){
            error += "Prefix is required";
        }
        
        // Validet data
        if (error != ""){
            $("#myModal").find(".modal-body").html(error);
            $('#myModal').modal({'show': true});
            return false;
        }
    });
    
    // Start Normalizer
    $("#normalizer-form").on("submit", function(event){
        var master = [];
        var others = [];
        var customSelected = [];
        var othersNames = [];
        var masterName = [];
        
        $("#questions").children("li").each(function(){
            var file = $(this).children("a.file_name_list");
            var check = $(this).find("input[name='question']");
            var id = file.data("id");
            var name = file.data("name");
            
            // Fill temp arrays
            if (file.hasClass("active")){
                master.push(id);
                masterName.push(name);
            }else{
                others.push(id);
                othersNames.push(name);
            }
        });
        
        //Check list custom selected
        var checkSelected = master[0];        
        $("ul.all[data-id='"+ checkSelected +"']").children("li").each(function(){
            if ($(this).data("selected") == 1){
                customSelected.push($(this).text()+"|");
            }
        });

        // Fill inputs hidden
        $("#masterId").val(master.join());
        $("#referenceId").val(others.join());
        $("#customSelected").val(customSelected.join());
        $("#savFileName").val(othersNames.join());
        $("#masterFileName").val(masterName.join());
        
        
        // Validate
        if (master.length == 0){
            $("#myModal").find(".modal-body").html("Select Master");
            $('#myModal').modal({'show': true});
            
            resetHidden();
            
            return false;
        }
        if (others.length == 0){
            $("#myModal").find(".modal-body").html("You don't have reference files");
            $('#myModal').modal({'show': true});

            resetHidden();

            return false;
        }
    });
    
    //Modal Error
    $("#modalError").dialog({
        autoOpen: false,
        modal: true,
        buttons: {
            "Ok": function(){
                $(this).dialog( "close" );        
            }
        }
    });



    // Click on the lists
    $("#bucket_list li a").on("click", function(event){
        event.preventDefault();
        var bucketName = $(this).data("value");
        var params = {
            'bucketName':bucketName
        };
        searchPrefix(params);
        searchFile(params);
    });

    $("#prefix_list").on("click", "a", function(event){
        var params = {
            'bucketName' : $(this).data("bucket"),
            'prefixName' : $(this).text()
        };
        searchFile(params);
    });

    // Short the file names
    $("#questions").children("li").each(function(){
        var filenameCont = $(this).find(".file_name");
        var filename = filenameCont.text();
        var name = filename.split("/");
        var finalName = name[name.length-1];
        
        filenameCont.text(finalName);
    });
});

function searchPrefix(params){
    //Find prefixes by bucket name
    $.ajax({
      url: "/questions/searchPrefix.do",
      data: params
    }).done(function(data) {
        $("#prefix_list").html("");
        for(i in data){
            var op = "<li class='selectable_item'><a data-bucket='"+params.bucketName+"'>"+data[i]+"</a></li>";
            $("#prefix_list").append(op);
        }
    });
}

function searchFile(params){
    //Find file by prefix and bucket name
    $.ajax({
      url: "/questions/searchFiles.do",
      data: params
    }).done(function(data) {
    $("#questions").html("");
        for(i in data){
            var fileName = data[i].inputKey;
            var idx = fileName.lastIndexOf('/');
            if(idx>-1){
                fileName = data[i].inputKey.substring(idx+1);
            }
            var li = $("<li>");
            var file = $("<a href='#'>");
            file.addClass("file_name_list");
            file.attr("data-id",data[i].id);
            file.attr("data-name",data[i].inputKey);
            file.append("<div class='file_name'>"+fileName+"</div>");
            file.append("<div class='file_opts hide'><i class='icon-ok'></i><span class='showQuestions' data-id='"+data[i].id+"'>Custom</span></div>");
            li.append(file);

            var questions = $("<ul>");
            questions.attr("data-id",data[i].id);
            questions.addClass("all hide");
            for(j in data[i].questionList){
                var question = "<li data-value='value"+i+"' data-selected='0'>"+data[i].questionList[j]+"</li>";
                questions.append(question);
            }
            li.append(questions);
            $("#questions").append(li);
        }
    });
}

function checkChecked(){
    $("#questions").find("li").each(function(){
    	if ($(this).find("input[name='question']").is(":checked")){
    		$(this).find("input[name='question']").parent("li").find("span").show();
    	}else{
    		$(this).find("input[name='question']").parent("li").find("span").hide();
    	}
    });
}

function fillSelects(id){
    var id = id;

    // Clean Selects
    cleanSelects();

    // Fill ID
    $("#idOpened").val(id);

    // Fill Selects
    $("#questions").find("ul.all[data-id="+id+"]").children("li").each(function(){
        var name = $(this).text(),
            value = $(this).data("value"),
            selected = $(this).data("selected");

        var option = $("<option value='" + value + "'> " + name + " </option>");

        if (selected == 0){
            $("#filesLeft").append(option);
        }else{
            $("#filesRight").append(option.clone());
            $("#filesLeft").append(option.clone().attr("disabled", "disabled"));
        }
        
    });
}
function cleanSelects(){
    $("#idOpened").val("");
    $("#filesLeft").html("");
    $("#filesRight").html("");
}

function transferFiles(action){
    var action = action || "";

    if (action == "selectSingle"){
        $("#filesLeft").children('option:selected').clone().appendTo($("#filesRight"));
        $("#filesLeft").children('option:selected').attr("disabled", "disabled").removeAttr("selected");
        $("#filesRight").find("option").removeAttr("selected");
    }

    if (action == "selectAll"){
        $("#filesLeft").children('option').not(":disabled").clone().appendTo($("#filesRight"));
        $("#filesLeft").children('option').attr("disabled", "disabled").removeAttr("selected");
        $("#filesRight").find("option").removeAttr("selected");
    }

    if (action == "unSelectSingle"){
        $("#filesRight").children('option:selected').each(function(){
            var id = $(this).val();            
            $("#filesLeft").children('option[value='+id+']').removeAttr("disabled");
            $(this).remove();
        });
    }
    
    if (action == "unSelectAll"){
        $("#filesRight").children('option').each(function(){
            var id = $(this).val();            
            $("#filesLeft").children('option[value='+id+']').removeAttr("disabled");
            $(this).remove();
        });
    }
}

function saveTransfers(id){
    var id = id || "";

    $("#questions").find("ul.all[data-id="+id+"]").html("");
    $("#filesLeft").find("option").each(function(){
        var optionValue = $(this).val(),
            optionTxt = $(this).text(),
            li = $("<li data-value='" + optionValue + "'>" + optionTxt + "</li>");

        if ($(this).is(":disabled")){
            li.attr("data-selected", 1);
        }else{
            li.attr("data-selected", 0);
        }

        $("#questions").find("ul.all[data-id="+id+"]").append(li);          
    });
}

function resetHidden(){
    $("#masterId").val("");
    $("#referenceId").val("");
    $("#customSelected").val("");
}